<?php      


/**
* 好友关系的相关操作
*/
class UCModRelation
{
    protected $_userid;
    public $_errno;
    public $_error;
    private $_last_bi_relation = false;
    private $_included = false;
    
    public function __construct($userid)
    {
        if( !$this->_included ) {
            require_once(dirname(__FILE__).'/../../../unified/SDOApiRelationService.php');
            require_once(dirname(__FILE__).'/../../../unified/SDOApiGroupService.php');
            require_once(dirname(__FILE__).'/../user/UCModUserInfo.php');
            require_once(dirname(__FILE__).'/UCModBlacklist.php');
            require_once(dirname(__FILE__).'/../../config/UCConfRelation.php');       
            require_once(dirname(__FILE__).'/../message/UCModMessageMgr.php');
            require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php'); 
            require_once(dirname(__FILE__).'/../feed/UCModFeed.php');
            require_once(dirname(__FILE__).'/../../libraries/UCLibStat.php'); 
            require_once(dirname(__FILE__).'/../../libraries/UCLibNewTip.php');
            $this->_included = true;
        }   
        $this->_userid = $userid;
    }
    
    public function initUser($userid)
    {
        $this->_userid = $userid;
    }
    
    private function _isSuccess($ret)
    {
        //UCLibLogger::debug($ret);
        $this->_errno = (is_array($ret) && array_key_exists('code', $ret))? $ret['code']:-1;
        $this->_error = (is_array($ret) && array_key_exists('msg', $ret))? $ret['msg']:'';
        return (is_array($ret) && $ret['status']==200 && $ret['code'] == 0)? true:false;
    }
    
    public function isLastBiRelation()
    {
        return $this->_last_bi_relation;
    }
    
    private function _addonUserInfo($ar_relation, $is_get_userinfo = false, $is_get_fans_num = false) {
//        UCLibLogger::debug($ar_relation);
        $ar_userlist = array();
        if( is_array($ar_relation) && array_key_exists('entry', $ar_relation) ) {
            foreach($ar_relation['entry'] as $relation) {
                if( array_key_exists('value', $relation) )
                    $ar_userlist[] = $relation['value']['fsdid'];
            }
        }
        
        if( $is_get_userinfo == true ) {
            $ar_info = UCModUserInfo::getUserInfos($ar_userlist, array(USERINFO_NICKNAME, USERINFO_AVATAR_45,USERINFO_AVATAR_170,
                 USERINFO_GENDER, USERINFO_LOCATION));
        }
        if( $is_get_fans_num == true ) {    
            $ar_fans_num = $this->getFansNumberByBatch($ar_userlist);
        }
        
        //UCLibLogger::debug($ar_fans_num); 
        
        if( is_array($ar_relation) && array_key_exists('entry', $ar_relation) ) {
            foreach($ar_relation['entry'] as &$relation) {
                if( isset($ar_fans_num[$relation['value']['fsdid']]) ) {
                    $relation['value']['fans_num'] = $ar_fans_num[$relation['value']['fsdid']];
                }
                
                $new_groups = array();                  
                if( isset($relation['value']['groups']) ) {
                    foreach( $relation['value']['groups'] as $group) {
                        $new_groups[] = $group['groupId'];  
                    }
                    $relation['value']['groups'] = $new_groups;
                }
                
                
                if( $ar_info != false && array_key_exists('value', $relation) && array_key_exists($relation['value']['fsdid'], $ar_info) ) {
                    $relation['value']['nick'] = $ar_info[$relation['value']['fsdid']][USERINFO_NICKNAME];
                    if(empty($relation['value']['nick']))
                        $relation['value']['nick'] = $relation['value']['fsdid'];
                    $relation['value']['avatar'] = $ar_info[$relation['value']['fsdid']][USERINFO_AVATAR_45];
                    $relation['value']['avatar_170'] = $ar_info[$relation['value']['fsdid']][USERINFO_AVATAR_170];
                    $relation['value']['gender'] = $ar_info[$relation['value']['fsdid']][USERINFO_GENDER];
                    
                    if( !empty($ar_info[$relation['value']['fsdid']][USERINFO_LOCATION]) ) {
                        $ar_location = UCLibLocation::getLocationPath($ar_info[$relation['value']['fsdid']][USERINFO_LOCATION]);
                        $prov = array_shift($ar_location);
                        //$prov = trim($prov, '市省');
                        if(!empty($ar_location)) {
                            $city = array_shift($ar_location);     
                            $relation['value']['location']    = "$prov,$city";        
                        } else {
                            $relation['value']['location']    = "$prov";        
                        }
                    }
                    else {
                        $relation['value']['location']    = '';      
                    }
                }
                $relation = $relation['value'];
                unset($relation['value']);
                unset($relation['sdid']);
            }
        } 
//        UCLibLogger::debug($ar_relation);                                             
        return $ar_relation;
    }
    /*
     array (
  'entry' => 
  array (
    0 => 
    array (
      'value' => 
      array (
        'sdid' => 110000308490,
        'groupNum' => 1,
        'groupId' => 150,
        'groupName' => '123123',
      ),
    ),*/ 
    private function _addonGroupInfo($ar_groups) {
        if( is_array($ar_groups) && array_key_exists('entry', $ar_groups) ) {
            foreach($ar_groups['entry'] as &$group) {
                $group = $group['value'];
                unset($group['value']);
            }
        }
        //UCLibLogger::debug($ar_groups);
        return $ar_groups;
    }
    
    public function getLastErrno() {
        return $this->_errno;
    }
    
    public function getLastError() {
        return isset($this->_error)?$this->_error:UCConfRelation::getErrorMessage($this->_errno);
    }
    
    private function _checkRelationPermision($target_userid) {
        //不能添加本人
        if( $target_userid == $this->_userid ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_IS_SELF;
            return false;
        }
        //检查我是否在对方黑名单中
        $mod_black = new UCModBlacklist($target_userid);
        $ret = $mod_black->getJudgePerson($this->_userid);
//        UCLibLogger::debug($ret);
//        UCLibLogger::debug($mod_black->getLastError());
        if( $ret == 1 ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_IS_BLACKED;
            return false;
        }

        //检查对方是否在我的黑名单中
        $mod_black->changeUserid($this->_userid);
        $ret = $mod_black->getJudgePerson($target_userid);
        if( $ret == 1 ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_IN_MY_BLACK;
            return false;
        }
        
        return true;
    }
    
    /**
    * 添加双向关注
    * 
    * @param long $target_userid
    * @return true/false
    */
    public function addBiRelation($target_userid) { 
        if( !$target_userid ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        if(!$this->_checkRelationPermision($target_userid)) {
            return false;
        }
        //不能关注已经关注过的用户
        $ret = $this->getRelationType(array($target_userid), UCConfRelation::RELATION_TYPE_BIFOLLOW);
        if( $ret !== false && $ret[$target_userid] == 1 ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_FOLLOWED;
            return false;
        }
        $ret1 = SDOApiRelationService::addRelation($this->_userid, $target_userid, array('appId'=>0));
        $ret2 = SDOApiRelationService::addRelation($target_userid, $this->_userid, array('appId'=>0));
            
        //双向关注，都发送通知
        if( $target_userid !=1235625354 && $this->_isSuccess($ret1) ) {                 
            $o_mgr = new UCModMessageMgr($sdid);
            $o_mgr->sendNotice("add_fri_feedback", $target_userid, array("usr_id"=>$this->_userid));
        }
        if( $target_userid !=1235625354 && $this->_isSuccess($ret2) ) {                 
            $o_mgr = new UCModMessageMgr($sdid);
            $o_mgr->sendNotice("add_fri_feedback", $this->_userid, array("usr_id"=>$target_userid));
        }

        return $this->_isSuccess($ret1) && $this->_isSuccess($ret2);
    }
    
    /**
    * 添加一个关注，且不加到任何分组
    * 
    * @param long $target_userid
    * @return true/false
    */
    public function addRelation($target_userid) { 
        if( !$target_userid ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
          
        if(!$this->_checkRelationPermision($target_userid)) {
            return false;
        }  
        
        //不能关注已经关注过的用户
        $ret = $this->getRelationType(array($target_userid), UCConfRelation::RELATION_TYPE_FOLLOW);
        if( $ret !== false && $ret[$target_userid] == 1 ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_FOLLOWED;
            return false;
        }
        //不能加超过2000个好友
        $follow_count = $this->getRelationFollowCount();
        if( $follow_count !== false && $follow_count >= UCConfRelation::RELATION_NUM_MAX_LIMIT ) {
            $this->_errno = UCConfRelation::ADD_RELATION_ERROR_NUM_LIMIT;
            return false;
        }

        //TODO: appId申请
        $ret = SDOApiRelationService::addRelation($this->_userid, $target_userid, array('appId'=>0));
        UCLibLogger::debug('------ addRelation -----');
        if( $this->_isSuccess($ret) ) {
            $mod_feed = new UCModFeed($this->_userid);

            $mod_feed->addOneFeed(array(
                'activityType' => UCConfFeed::FEED_TYPE_FRIEND,
                'friendSdid' => $target_userid,
                'inviteType' => '99',
                'bidrection' => false,
                'reviewable' => false
            ));
            
            //如果对方已经关注过我，则发送通知，否则发送请求
            $judge_ret = $this->getRelationType(array($target_userid), UCConfRelation::RELATION_TYPE_BE_FOLLOWED);
            UCLibLogger::debug('------ judge_ret -----');
            UCLibLogger::debug($judge_ret);
            if( $judge_ret !== false && $judge_ret[$target_userid] == 1 ) {
                $this->_last_bi_relation = true;
                //如果对方已经关注过我，则发送通知
                $o_mgr = new UCModMessageMgr($sdid);
                $o_mgr->sendNotice("add_fri_feedback", $target_userid, array("usr_id"=>$this->_userid));
            }
            if( $judge_ret !== false && $judge_ret[$target_userid] == 0 ) {
                $this->_last_bi_relation = false;
                //如果对方没有关注过我，则发送请求
                UCLibStat::action(UC_RELATION_ACTION_ADD);
                $this->requestRelation($target_userid);
            }
            
            $o = new UCLibNewTip ($target_userid);
            $o->add(UCLibNewTip::MEMCACHE_KEY_FANS);
        }
        
        return $this->_isSuccess($ret);
    }
    
    /**
    * 获取关注的用户总数
    * @return false/count
    */
    public function getRelationFollowCount() {
        if( $this->_userid == 1235625354 )
            return '2012+';
        $ret = $this->getRelationFollow(1, 0);
        if( !$ret )
            return false;
        return intval($ret['totalResults']); 
    }
    
    /**
    * 获取粉丝总数
    * @return false/count
    */
    public function getRelationReverseCount() {
        if( $this->_userid == 1235625354 )
            return '2012+';
        $ret = $this->getRelationReverse(1, 0);
        if( !$ret )
            return false;
        return intval($ret['totalResults']);
    }
    
    /**
    * 查询正向关系
    * 根据用户数字账号查询该用户关注的用户关系列表，支持分页。
    * 
    * @param int $start
    * @param int $count
    * @return Array
    * 'entry' => 
      array (
        0 => 
        array (
          'lastModifiedTime' => 1269936004000,
          'createTime' => 1269936004000,
          'sdid' => 110000308490,
          'appId' => 6,
          'fsdid' => 100,
          'relationId' => 100668,
          'appName' => '__',
          'remarks' => '',
          'groups' => 
          array (
            0 => 0,
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 101,
            5 => 0,
            6 => 0,
            7 => 0,
          ),
          'nick' => '',
          'avatar' => 'http://ipic.staticsdo.com/v1/images/avatar/temp1.gif',
          'gender' => 0,
        ),
    */
    public function getRelationFollow($start=0, $count=20, $is_get_userinfo = false, $is_get_fans_num = false) {
        if($this->_userid == 1235625354 && ($count==0 || $count > 2012) )
            $count=2012;
        $ret = SDOApiRelationService::getRelationFollow($this->_userid, array("startIndex"=>$start, "count"=>$count));
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'],$is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
    * 返回一个用户下所有的分组信息，支持分页
    * 
    */
    public function getPersonGroups() {
        $ret = SDOApiGroupService::getPersonGroups($this->_userid);   
        return $this->_isSuccess($ret)?$this->_addonGroupInfo($ret['data']):false;
    }
    
    /**
    * 根据用户数字账号查询该用户关注的用户关系列表不包含分组关系信息，支持分页。
    * 
    * @param int $start
    * @param int $count
    * @return Array
    */
    public function getFollowsDistinct($start=0, $count=20,$is_get_userinfo = false, $is_get_fans_num = false) {
        $ret = SDOApiRelationService::getRelationFollowDistinct($this->_userid, array("startIndex"=>$start, "count"=>$count)); 
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'], $is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
    * 根据用户数字账号查询关注该用户的用户关系列表，支持分页。
    * 
    * @param int $start
    * @param int $count
    * @return Array
    */
    public function getRelationReverse($start=0, $count=20,$is_get_userinfo = false, $is_get_fans_num = false) {
        $ret = SDOApiRelationService::getRelationReverse($this->_userid, $start, $count);
        if( $this->_userid == 1235625354 && isset($ret['data']['totalResults']) )
            $ret['data']['totalResults'] = '2012+';
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'],$is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
    * 根据用户数字账号查询和该用户有双向关系的所有用户关系列表，支持分页。
    * 
    * @param int $start
    * @param int $count
    * @return Array
    */
    public function getBiRelation($start=0, $count=20, $is_get_userinfo=false, $is_get_fans_num=false) {
        $ret = SDOApiRelationService::getBiRelation($this->_userid, array("startIndex"=>$start, "count"=>$count)); 
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'], $is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
     * 共同好友推荐
     * 根据用户数字账号搜索与该用户具有最多共同好友（双向关系）的用户列表，按共
     * 同好友数量最多到最少返回，支持最少的共同好友数量设置。注意：该API 仅仅针
     * 对双向关系。
     * @param Long $commonFriendsNumber  是 最少的共同好友数量 
     */
    public function getCommonFriends($common_friend_num = 3) {
        $ret = SDOApiRelationService::getCommonFriends($this->_userid, array('commonFriendsNumber'=>$common_friend_num)); 
        return $this->_isSuccess($ret)?$ret['data']:false;
    }
    
    /**
    * 获取该用户跟 $target_userid 共同关注的人
    * 
    * @param long $target_userid
    */
    public function getCommonFollows($target_userid, $count=6)
    {   
        if( !$target_userid ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $my_follows = $this->getRelationFollow(0,0);
        if( $my_follows === false )
            return false;
        
        $_user = $this->_userid;
        $this->initUser($target_userid); 
        $his_follows = $this->getRelationFollow(0,0);
        $this->initUser($_user);
        if( $his_follows === false ) {
            return false;
        }
        if( $my_follows['totalResults'] == 0 || $his_follows['totalResults'] == 0 )
        {
            return array();
        }
        $my_follows_id = array();
        foreach($my_follows['entry'] as &$relation) {
            $my_follows_id[] = $relation['fsdid'];
        }
        $common_follows = array();
        foreach($his_follows['entry'] as $relation) {
            unset($relation['lastModifiedTime']);
            unset($relation['createTime']); 
            unset($relation['appId']);    
            unset($relation['remarks']);
            unset($relation['groups']);
            unset($relation['fans_num']); 
            if( in_array($relation['fsdid'], $my_follows_id) ) {
                $common_follows[] = $relation;
            }   
        }
        if( !empty($common_follows) && count($common_follows) > $count) {
            $common_follows = array_slice($common_follows, 0, $count);
        }
        
        return $common_follows;
    }
    
    /**
    * 根据用户数字账号等信息删除对$follow_userid 的关注。
    * 
    * @param mixed $follower_userid
    * @return boolean
    */
    public function deleteRelation($follow_userid) {
        if( !$follow_userid ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiRelationService::deleteRelation($this->_userid, $follow_userid); 
        return $this->_isSuccess($ret);
    }
    
    public function getFansNumberByBatch($ar_userid) {
        if( empty($ar_userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiRelationService::getFansNumberByBatch(implode(',',$ar_userid));
        if(!$this->_isSuccess($ret))
            return false;                                           
        $ar_fans_num = array();
        if( !empty($ret['data']) && $ret['data']['totalResults']>0 ) {
            foreach($ret['data']['entry'] as $f) {
                if( $f['value']['sdid'] == 1235625354 ) {
                    $ar_fans_num[$f['value']['sdid']] = '2012+';
                } else {
                    $ar_fans_num[$f['value']['sdid']] = $f['value']['fansNum'];
                }
            }
        }
        return $ar_fans_num; 
    }
    
    public function deleteFan($userid) {
        if( empty($userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiRelationService::deleteRelation($userid, $this->_userid); 
        return $this->_isSuccess($ret);
    }
    
    /**
    * 根据用户数字账号和分组号从指定分组中删除关系。
    * 
    * @param long $gid
    * @param string $follow_userid
    * @return boolean
    */
    public function deleteRelationOutGroup($gid, $follow_userid) {
        if( empty($gid) || empty($follow_userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiRelationService::deleteRelationOutGroup($this->_userid, $follow_userid, $gid); 
        return $this->_isSuccess($ret);
    }
    
    /**
    * 根据用户数字账号和关注者账号把一条关系从一个用户指定分组中移到另一个用户指定的分组中。
    * 
    * @param string $follow_userid
    * @param int $old_gid
    * @param int $new_gid
    * @return boolean
    */
    public function modifyRelationGroupId($follow_userid, $old_gid, $new_gid) {
        if( empty($follow_userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiGroupService::removeRelationOutGroup($this->_userid, $follow_userid, $old_gid, $new_gid); 
        return $this->_isSuccess($ret);
    }
    
    /**
    * 根据用户数字账号和关注者账号把一条关系从一个用户指定分组中移到另一个用户指定的分组中。
    * 
    * @param string $follow_userid
    * @param long $gid
    * @return boolean
    */
    public function addRelationToGroup($follow_userid, $gid) {
        if( empty($follow_userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        
        if(!$this->_checkRelationPermision($target_userid)) {
            return false;
        }
        $ret = SDOApiRelationService::addRelationToGroup($this->_userid, $follow_userid, $gid); 
        return $this->_isSuccess($ret);
    }
    
    /**
    * 根据用户数字账号和关注者账号把关系从一个用户指定分组中批量移到另一个用户指定的分组中。
    * 
    * @param string $fids 用,分隔的fid串列表 id1,id2,id3
    * @param long $gid
    * @return boolean
    */
    public function addRelationsToGroup($fids, $gid) {
        if( empty($fids) || empty($gid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        //if(!$this->_checkRelationPermision($target_userid)) {
        //    return false;
        //}
        $ar_fid = explode(',', $fids);
        if( empty($ar_fid) && $empty($ar_fid[0]) ) {
            return false;
        }
        foreach($ar_fid as $fid) {
            $fid = intval($fid);
            if($fid <= 0)
                continue;
            $ret = $this->addRelationToGroup($fid, $gid);
            if( $ret === false )
                return false;
        }                    
        return true;
    }
    
    /**
    * 列出所有关注了我而我没关注的人
    * 
    */
    public function getCandidatePeople($is_get_userinfo = false, $is_get_fans_num = false) {
        $ret = SDOApiRelationService::getCandidatePeople($this->_userid); 
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'], $is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
    * 列出所有我关注了的却没关注我的人
    * 
    */
    public function getRecommendPeople($is_get_userinfo = false, $is_get_fans_num = false) {
        $ret = SDOApiRelationService::getRecommendPeople($this->_userid); 
        return $this->_isSuccess($ret)?$this->_addonUserInfo($ret['data'], $is_get_userinfo, $is_get_fans_num):false;
    }
    
    /**
    * 根据分组id 返回一个分组对象
    * 
    * @param long $gid
    * @return Array
    */
    public function getGroup($gid, $type = 0) {
        $ret = SDOApiGroupService::getGroup($gid, $this->_userid, $type); 
        return $this->_isSuccess($ret)?$ret['data']:false;
    }
    
    /**
    * 批量判断一个用户和一个列表中用户的关系 
    * 
    * @param mixed $ar_userids
    * @param mixed $judge_type  1 表示关注，2 表示被关注，3 表示时双向关系
    * @return Array {
    *   [fsdid1] => 0/1
    *   [fsdid] => 0/1
    * }
    * 
    */
    public function getRelationType($ar_userids, $judge_type) {
        if( empty($ar_userids) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiRelationService::getRelationType($this->_userid, implode(',',$ar_userids), $judge_type);
        if( $this->_isSuccess($ret) === false )
            return false;
        $tmp_ret_ar = SDOApiHelper::getArrayResult($ret);
        $ret_ar = array();
        foreach($tmp_ret_ar as $tmp_ret) {
            $ret_ar[$tmp_ret['fsdid']] = $tmp_ret['judgeResult'];
        }
        return $ret_ar;
    }
    
    /**
    * 判断一个用户和另一个用户的关系 
    * 
    * @param long $userid
    * @param int $judge_type  1 表示关注，2 表示被关注，3 表示时双向关系
    * @return false/ 0/1
    */
    public function getSingleRelationType($userid, $judge_type) {
        if( empty($userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = $this->getRelationType(array($userid), $judge_type);
        if( $ret === false )
            return false;
        return $ret[$userid];
    }
    
    /**
    * 添加一个新的关注分组
    * 
    * @param string $gname
    * @return false/ insert_id
    */
    public function addGroup($gname) {
        $groups = $this->getPersonGroups();
        if( $groups === false ) {
            return false;
        }
                                       
        if( $groups['totalResults'] > UCConfRelation::RELATION_GROUP_MAX_NUM ) {
            $this->_errno = UCConfRelation::ADD_GROUP_ERROR_EXCEED_MAX_NUM;
            return false;
        }
        $ret = SDOApiGroupService::addGroup($this->_userid, 0, $gname);
//        UCLibLogger::debug($ret);
        return $this->_isSuccess($ret)?$ret['data']['data']:false;
    }
    
    /**
    * 修改关注分组名
    * 
    * @param long $gid
    * @param string $gname
    * @return boolen
    */
    public function updateGroupName($gid, $gname) {
        if( empty($gid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiGroupService::updateGroupName($gid, $this->_userid, $gname);
        return $this->_isSuccess($ret);
    }
    
    /**
    * 删除一个指定 $gid 的分组
    * 
    * @param mixed $gid
    * @return boolen
    */
    public function deleteGroup($gid) {
        if( empty($gid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        $ret = SDOApiGroupService::deleteGroup($gid, $this->_userid);
        return $this->_isSuccess($ret);
    }
    
    /**
    * 发送添加好友请求
    * * 一周内请求过的不能再发请求
    * 
    * @param long $target_userid 需要发送请求的好友
    * @return false/true
    */
    public function requestRelation($target_userid) {
        if( empty($target_userid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        //黑名单内不能发请求
        if( !$this->_checkRelationPermision($target_userid) ) {
            return false;
        }
        
        $cache = new UCLibCache(UCConfRelation::RELATION_REQUEST_MEMCACHE_CHANNEL);
        //发送过请求的则1周内不允许再发
        $ar_in_cached = $this->getRequestedCache();
        $time = time();
        if( $ar_in_cached !== false && isset($ar_in_cached[$target_userid]) ) 
        {
            $this->_errno = UCConfRelation::REQUEST_RELATION_ERROR_REQUESTED;
            return false;
        }
        UCLibLogger::debug($ar_in_cached);
        
        $o_mgr = new UCModMessageMgr($this->_userid);
        $ret = $o_mgr->sendRequest(UCConfRelation::RELATION_REQUEST_TYPE, $target_userid);
        if( !$ret ) {
            $this->_errno = UCConfRelation::REQUEST_RELATION_ERROR;
            $this->_error = $o_mgr->getErrorInfo();
            return false;
        }
        //成功，写cache，以免重复请求
        if( !$ar_in_cached ) {
            $ar_in_cached = array();
        }
        $ar_in_cached[$target_userid] = time();
        $cache = new UCLibCache(UCConfRelation::RELATION_REQUEST_MEMCACHE_CHANNEL);
        $cache->write(UCConfRelation::getRequestedCacheKey($this->_userid), $ar_in_cached);
        
  
        $this->_errno = 0;
        return $ret;
    }
    
    /**
    * 获取用户发送过好友请求的1周缓存
    */
    public function getRequestedCache() {
        $cache = new UCLibCache(UCConfRelation::RELATION_REQUEST_MEMCACHE_CHANNEL);
        $ar_in_cached = $cache->read(UCConfRelation::getRequestedCacheKey($this->_userid));
        if( !$ar_in_cached )
            return array();
        $time = time();
        foreach($ar_in_cached as $userid => $cached_time) {
            if( ($time-$cached_time) > UCConfRelation::RELATION_REQUEST_MEMCACHE_TIMEOUT ) {
                unset($ar_in_cached[$userid]);
            }
        }
        return $ar_in_cached;
    }
    
    /**
    * 批量修改某个好友的分组
    * 
    * @param long $fid
    * @param array $ar_groups 要重新设置的分组列表
    * @return bool
    */
    public function updateRelationGroupIdByBatch($fid, $ar_groups)
    {
        if( empty($fid) ) {
            $this->_errno = UCConfRelation::RELATION_INVALID_PARAM;
            return false;
        }
        if( empty($ar_groups) ) {
            $ar_groups = array(0);
        }
//        UCLibLogger::debug(implode(',', $ar_groups));
        $ret = SDOApiRelationService::updateRelationGroupIdByBatch($this->_userid,
            $fid, implode(',', $ar_groups));
        return $this->_isSuccess($ret);
    }
    
    /**
    * 获取用户双向好友的数量，勋章用
    */
    public function getBiRelationCount()  {
        $ret = $this->getBiRelation(0, 0);
        if( $ret === false ) {
            return false;
        }
        return intval($ret['totalResults']);
    }
    
}

function __follow_cmp($f1, $f2){
    if( $f1['fsdid'] == $f2['fsdid'] )
        return 0;
    return -1;
}
/*
$o = new UCModRelation(110000308490);
$ret = $o->getBiRelation(0, 100);
var_dump($ret);
var_dump($o->_errno);
*/

?>